<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>商品管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="icon" href="/images/favicon.ico">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">关键字</label>
                            <div class="layui-input-inline">
                                <label for="keyword"></label><input id="keyword" type="text" name="keyword"
                                                                    autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button id="searchBtn" type="button" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn">
                                <i class="layui-icon"></i> 搜 索
                            </button>
                            <button id="delBtn" type="button" class="layui-btn"><i class="layui-icon">&#xe640;</i>回收站
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm data-add-btn" lay-event="add">添加商品</button>
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="start">上架</button>
                <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="stop">下架</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="del">批量删除</button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>


        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn layui-btn-radius layui-btn-xs" lay-event="edit">修改</a>
            <a class="layui-btn layui-btn-xs layui-btn-radius layui-btn-danger" lay-event="delete">删除</a>
            <a class="layui-btn layui-btn layui-btn-radius layui-btn-normal layui-btn-xs" lay-event="upload">上传附件</a>
        </script>

        <!-- 定义附件上传的模板 -->
        <script type="text/html" id="uploadForm">
            <form class="layui-form" action="" lay-filter="uploadForm">
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-warm" id="pImgs"><i class="layui-icon"></i>商品图片
                        </button>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览图：
                            <div class="layui-upload-list" id="imgList"></div>
                        </blockquote>
                    </div>
                </div>
                <input type="hidden" name="id">
                <input type="hidden" id="ids" name="ids">
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button id="addImgBtn" type="button" class="layui-btn" lay-submit="" lay-filter="demo1">立即提交
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </script>

        <!-- 定义新增时的模板 -->
        <script type="text/html" id="productForm">
            <form class="layui-form" action="" lay-filter="productForm">
                <input type="hidden" id="id" name="id">

                <div class="layui-form-item">
                    <label class="layui-form-label">一级分类</label>
                    <div class="layui-input-inline">
                        <select id="firstSelect" lay-filter="topCategory"></select>
                    </div>
                    <label class="layui-form-label">二级分类</label>
                    <div class="layui-input-inline">
                        <select id="secondSelect" name="cateId"></select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品名称</label>
                    <div class="layui-input-inline">
                        <label><input type="text" name="name" lay-verify="required" placeholder="请输入商品名称"
                                      autocomplete="off" class="layui-input"></label>
                    </div>
                    <label class="layui-form-label">商品价格</label>
                    <div class="layui-input-inline">
                        <label><input type="number" name="price" lay-verify="required|number" placeholder="请输入商品价格"
                                      autocomplete="off" class="layui-input"></label>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品数量</label>
                    <div class="layui-input-inline">
                        <label><input type="number" name="num" lay-verify="required|number" placeholder="请输入商品数量"
                                      autocomplete="off" class="layui-input"></label>
                    </div>
                    <label class="layui-form-label">商品颜色</label>
                    <div class="layui-input-inline">
                        <label><input type="text" name="color" lay-verify="required" placeholder="请输入商品颜色"
                                      autocomplete="off" class="layui-input"></label>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label><input type="hidden" name="firstImg" id="firstImg"></label>
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-normal" id="fImg"><i class="layui-icon"></i>上传封面图
                        </button>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">相关描述</label>
                    <div class="layui-input-block">
                        <label><textarea name="info" id="info" placeholder="请输入相关描述" class="layui-textarea"></textarea></label>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button id="saveBtn" type="button" class="layui-btn" lay-submit="" lay-filter="demo1">立即提交
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </script>

    </div>
</div>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js" charset="utf-8"></script>
<script th:inline="none">
    layui.use(['form', 'table', 'layer', 'upload', 'common'], function () {
        let $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layer = layui.layer,
            upload = layui.upload;

        // 搜索按钮绑定事件
        $("#searchBtn").on("click", function () {
            // table表格渲染数据
            table.render({
                elem: '#currentTableId',
                url: '/product/list', // 发送请求的地址
                toolbar: '#toolbarDemo',
                where: {
                    keyword: $("#keyword").val()
                },
                cols: [[
                    {type: 'checkbox', field: 'left'},
                    {field: 'id', title: 'ID', sort: true, width: 72},
                    {field: 'name', title: '商品名称', width: 269},
                    {field: 'firstImg', title: '首页图',  templet: function (d) {
                        return "<img src=" + d.img + " width='58px' height='36px' class='layui-card'>"
                    }, width: 113},
                    {field: 'price', title: '商品价格', sort: true, width: 113, style: 'color: red;'},
                    {field: 'show', title: '是否上架', width: 105, style: 'color: deeppink;'},
                    {field: 'color', title: '颜色', width: 172},
                    {title: '操作', toolbar: '#currentTableBar', align: "center"}
                ]],
                limits: [10, 15, 20, 25, 50, 100],
                limit: 10,
                page: true,
                skin: 'line'
            }); //end table.render
        }).click(); //end $("#searchBtn")

        // 搜索按钮绑定事件
        $("#delBtn").on("click", function () {
            // table表格渲染数据
            table.render({
                elem: '#currentTableId',
                url: '/product/del/list', // 发送请求的地址
                where: {
                    keyword: $("#keyword").val()
                },
                cols: [[
                    {field: 'id', title: 'ID', sort: true, width: 92},
                    {field: 'name', title: '商品名称', width: 292},
                    {field: 'price', title: '商品价格', sort: true},
                    {field: 'num', title: '商品数量', sort: true},
                    {field: 'color', title: '颜色'}
                ]],
                limits: [10, 15, 20, 25, 50, 100],
                limit: 10,
                page: true,
                skin: 'line'
            }); //end table.render
        }); //end $("#searchBtn")


        let uploadFile = function () {
            // 封面图片上传
            upload.render({
                elem: '#fImg'
                , url: '/product/firstImg'
                , accept: 'file' //普通文件
                , done: function (res) {
                    if (res.code === 0) {
                        $("#firstImg").val('');
                        $("#firstImg").val(res.data.src);
                    } // end if
                } //end done
            }); //end upload
        }

        // 保存按钮绑定事件
        $("body").on("click", "#saveBtn", function () {
            // 发送请求把数据推送后台
            $.post("/product/save", form.val("productForm"), function () {
                // 请求成功后  1、关窗口，2、点搜索
                layer.closeAll();
                $("#searchBtn").click();
                infoMsg("添加成功！");
            }); //end $.post
        }); //end $("#saveBtn")

        // 提示信息
        let infoMsg = function (info) {
            layer.msg(info, {
                icon: 1,
                time: 1200
            });
        }
        let infoErrorMsg = function (info) {
            layer.msg(info, {
                icon: 5,
                time: 1200
            });
        }

        // 表格操作工具条时间
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') { // 点的是编辑
                $.get("/category/child", {id: 0}, function (categories) {
                    layer.open({
                        type: 1,
                        title: "修改商品",
                        area: ["660px", "500px"],
                        content: $("#productForm").html()
                    });
                    $.each(categories, function (i, v) {
                        $("#firstSelect").append("<option value='" + v.id + "'>" + v.name + "</option>");
                    });
                    $.post("/product/edit/" + obj.data.id, function (product) {
                        uploadFile();
                        $("#firstSelect").val(product.topCategory);
                        loadSubCategory(function () {
                            // 渲染表单
                            form.val("productForm", product);
                        });
                    });
                });
                // 渲染表单
                form.render();
                infoMsg("更新成功！");
            } //end if

            if (obj.event === 'delete') { // 点的是删除
                layer.confirm("您确定要删除该商品吗？", function () {
                    $.post("/product/del", {id: obj.data.id}, function () {
                        // 关窗口
                        layer.closeAll();
                        infoMsg("删除成功！");
                        // 重现渲染一遍table表格数据
                        $("#searchBtn").click();
                    }); //end $.post
                }); //end layer.confirm
            } // end if

            if (obj.event === 'upload') { // 点的是上传附件
                $.get("/product/attachment/" + obj.data.id, function (l) {
                    layer.open({
                        type: 1,
                        title: "上传附件",
                        area: ["420px", "320px"],
                        content: $("#uploadForm").html()
                    });
                    $.each(l, function (i, v) {
                        $('#imgList').append('<img width="50px" height="50px" src="' + v.pathView + '"class="layui-upload-img">');
                    });
                    let ids = "";
                    upload.render({
                        elem: '#pImgs',
                        url: '/product/imgs',
                        multiple: true,
                        before: function (o) {
                            o.preview(function (index, file, result) {
                                $('#imgList').append('<img width="50px" height="50px" src="' + result + '"class="layui-upload-img">');
                            });
                        },
                        done: function (o) {
                            // 记录每次上传后的结果
                            if (ids !== "") {
                                ids += ",";
                            }
                            ids += o.data.id;
                            console.log(ids);
                        }
                    });
                    $("#addImgBtn").on("click", function () {
                        $.post("/product/attr", {ids: ids, pId: obj.data.id}, function () {
                            layer.closeAll();
                            infoMsg("上传成功！");
                        });
                    });
                });
                // 渲染表单
                form.render();
            } // end if

        }); //end tool(currentTableFilter)


        // 根据选的中一级分类加载二级分类
        let loadSubCategory = function (fn) {
            $.get("/category/child", {id: $("#firstSelect").val()}, function (categories) {
                $("#secondSelect").html("");
                $.each(categories, function (i, v) {
                    $("#secondSelect").append("<option value='" + v.id + "'>" + v.name + "</option>");
                });
                form.render();
                if (fn != null) {
                    fn();
                }
            });
        }

        // 切换一级分类
        form.on("select(topCategory)", function () {
            loadSubCategory();
        });

        //监听表格复选框选择
        table.on('toolbar(currentTableFilter)', function (obj) {

            if (obj.event === 'add') { // 点的是新增
                // 先查所有的一级分类
                $.get("/category/child", {id: 0}, function (categories) {
                    layer.open({
                        type: 1,
                        title: "添加商品",
                        area: ["660px", "500px"],
                        content: $("#productForm").html()
                    });
                    $.each(categories, function (i, v) {
                        $("#firstSelect").append("<option value='" + v.id + "'>" + v.name + "</option>");
                    });
                    loadSubCategory();
                    uploadFile();
                    // 渲染表单
                    form.render();
                }); //end get
            }

            if (obj.event === 'start') { // 点的是上架
                layer.confirm("您确定要上架这些商品吗？", function () {
                    let checkStactus = table.checkStatus('currentTableId');
                    let data = checkStactus.data;
                    let ids = [];
                    $.each(data, function (i, v) {
                        ids[i] = v.id;
                    });
                    console.log(ids);
                    if (ids.length === 0) {
                        infoErrorMsg("请选择你要上架的商品！");
                    } else {
                        $.post("/product/start", {ids: ids}, function () {
                            // 关窗口
                            layer.closeAll();
                            infoMsg("上架成功！");
                            // 重现渲染一遍table表格数据
                            $("#searchBtn").click();
                        }); //end $.post
                    }
                }); //end layer.confirm
            } // end if

            if (obj.event === 'stop') { // 点的是下架
                layer.confirm("您确定要下架这些商品吗？", function () {
                    let checkStactus = table.checkStatus('currentTableId');
                    let data = checkStactus.data;
                    let ids = [];
                    $.each(data, function (i, v) {
                        ids[i] = v.id;
                    });
                    console.log(ids);
                    if (ids.length === 0) {
                        infoErrorMsg("请选择你要下架的商品！");
                    } else {
                        $.post("/product/stop", {ids: ids}, function () {
                            // 关窗口
                            layer.closeAll();
                            infoMsg("下架成功！");
                            // 重现渲染一遍table表格数据
                            $("#searchBtn").click();
                        }); //end $.post
                    }
                }); //end layer.confirm
            } // end if

            if (obj.event === 'del') { // 点的是下架
                layer.confirm("您确定要删除这些商品吗？", function () {
                    let checkStactus = table.checkStatus('currentTableId');
                    let data = checkStactus.data;
                    let ids = [];
                    $.each(data, function (i, v) {
                        ids[i] = v.id;
                    });
                    console.log(ids);
                    if (ids.length === 0) {
                        infoErrorMsg("请选择你要删除的商品！");
                    } else {
                        $.post("/product/delAll", {ids: ids}, function () {
                            // 关窗口
                            layer.closeAll();
                            infoMsg("删除成功！");
                            // 重现渲染一遍table表格数据
                            $("#searchBtn").click();
                        }); //end $.post
                    }

                }); //end layer.confirm
            } // end if

        });


    }); //end layui.use
</script>

</body>
</html>